package com.cnc.service.Impl;

import com.cnc.dao.CourseDetailMapper;
import com.cnc.pojo.CourseDetail;
import com.cnc.service.CourseDetailService;
import com.cnc.utils.JsonUtil;
import com.cnc.utils.SqlUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class CourseDetailServiceImpl implements CourseDetailService {
    @Override
    public String add(String data) {
        CourseDetail cd = (CourseDetail)JsonUtil.JsonToObject(data, CourseDetail.class);
        switch (cd.getType()){
            case "1":
                cd.setType("第一章");
                break;
            case "2":
                cd.setType("第二章");
                break;
            case "3":
                cd.setType("第三章");
                break;
        }
        SqlSession sqlSession = SqlUtil.getSqlSession();
        CourseDetailMapper mapper = sqlSession.getMapper(CourseDetailMapper.class);
        int i = mapper.addCourseDetail(cd);
        sqlSession.commit();
        sqlSession.close();
        if(i!=0){
            return "添加成功！";
        }else {
            return "添加失败！";
        }
    }

    @Override
    public String getInfo(String cid) {
        SqlSession sqlSession = SqlUtil.getSqlSession();
        CourseDetailMapper mapper = sqlSession.getMapper(CourseDetailMapper.class);
        List<CourseDetail> info = mapper.getInfo(cid);
        List<String> chapterList = mapper.getChapter(cid);
        HashMap<String, List> map = new HashMap<>();
        chapterList.forEach(i->{
            List<CourseDetail> collect = info.stream().filter(c -> c.getType().equals(i)).collect(Collectors.toList());
            map.put(i,collect);
        });
        return JsonUtil.objectToJson(map);
    }
}
